package hot_100;

import java.util.List;

/**
 * @author: Darven
 * @createTime: 2025-10-01  16:34
 * @description: TODO
 */
public class P19 {
    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        ListNode a=head;
        for(int i=2;i<=5;i++){
            a.next=new ListNode(i);
            a=a.next;
        }

        P19 p19 = new P19();

        ListNode node = p19.removeNthFromEnd(head, 2);

        while (node!=null){
            System.out.println(node.val);
            node=node.next;
        }

    }

    // 递归解决计数问题
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode l=new ListNode(-1);
        l.next=head;
        int index=find(head,n);
        return l.next;
    }

    private int find(ListNode l, int n) {
        if(l==null){
            return 0;
        }

        int i = find(l.next, n);
        if(i==n){
            l.next=l.next.next;
        }
        return i+1;
    }
}
